package com.servlet.article;

import com.entity.Article;
import com.entity.Code;
import com.service.ArticleService;
import com.utils.JsonUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

/**
 * 根据文章标题进行模糊查询文章
 * 必选参数：title
 */
@WebServlet(name = "search", value = "/search")
public class Search extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //判断根据什么查询 ID title
//        String id = request.getParameter("id");
        String title = request.getParameter("title");

        ArticleService articleService = new ArticleService();
        JsonUtil jsonUtil = new JsonUtil();

        try {
//            if (id!=null){
//                //根据ID查询
//                Article article = articleService.findArticleById(Integer.parseInt(id));
//                Code code = new Code();
//                code.setData(article);
//                code.setCode("200");
//                code.setMsg("查询成功");
//                String s = jsonUtil.JavaToJson(code);
//                response.getWriter().print(s);
//
//            }else {
                //根据title模糊查询
                List<Article> articleByName = articleService.findArticleByName(title);
                Code code = new Code();
                code.setMsg("查询成功");
                code.setData(articleByName);
                code.setCode("200");
                String s = jsonUtil.JavaToJson(code);
                response.getWriter().print(s);

//            }
        }catch (Exception e){
            System.out.println("模糊标题查询错误："+e);
            Code code = new Code();
            code.setCode("403");
            code.setMsg("查询失败，请稍后再试");
            String s = jsonUtil.JavaToJson(code);
            response.getWriter().print(s);
        }



    }
}
